package cn.fl.system.controller;


import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.flow.service.IFlowService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.vo.SysOrgVO;
import net.sf.json.JSONArray;

/**
 * @Description: 组织架构表 控制层
 */
@Controller
@RequestMapping("/system/sysOrg")
public class SysOrgController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysOrgController.class);

	/**
	 * SysOrg 服务层BEAN
	 */
	@Autowired
	private ISysOrgService sysOrgService;
	
	/**
	 * 任务服务
	 */
	@Autowired
	private IFlowService flowService;
	
	@Autowired
    private ICstBscInfoService cstBscInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysOrg/sysSysOrglist");
		//公司级别
		List<KeyValueVO> searchSelectOrgTypCdList = this.sysOrgService.searchSysOrgTypCdList();
		if(searchSelectOrgTypCdList!=null){
			
			view.addObject("searchSelectOrgTypCdList", searchSelectOrgTypCdList);
		}
		return view;
	}
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toBnListPage.do", method = { RequestMethod.GET})
	public ModelAndView toBnListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysOrg/sysSysOrgForBnlist");
		return view;
	}
	
	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("oid");
		ModelAndView view = new ModelAndView("system/sysOrg/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "加载组织架构修改页面.",CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表点一次查一次
	 */
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String orgTypCd = request.getParameter("orgTypCd");
		try {
			//JSONArray jsonArray = this.sysOrgService.searchList(SysOrgConstant.SYS_ORG_CD_PID_INIT);
			JSONArray jsonArray = new JSONArray();
			if(StringUtils.isNotBlank(orgTypCd)){
				jsonArray = this.sysOrgService.searchOrgTreeByOrgCon("",orgTypCd, CurrentThreadContext.getCurrentSysCd()); 
			}else{
				jsonArray = this.sysOrgService.searchOrgTreeByOrgNm("", CurrentThreadContext.getCurrentSysCd()); 
			}
			BaseLogUtils.info(logger, "initList", "初始化组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
			return jsonArray;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "初始化组织架构列表页面失败.系统错误:"+e.getMessage(),CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	
	@RequestMapping(value = "/initForBnList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initForBnList(HttpServletRequest request, HttpServletResponse response) {
		String orgTypCd = request.getParameter("orgTypCd");
		try {
			//JSONArray jsonArray = this.sysOrgService.searchList(SysOrgConstant.SYS_ORG_CD_PID_INIT);
			JSONArray jsonArray = new JSONArray();
			if(StringUtils.isNotBlank(orgTypCd)){
				jsonArray = this.sysOrgService.searchOrgTreeByOrg("00000008",orgTypCd, CurrentThreadContext.getCurrentSysCd()); 
			}else{
				jsonArray = this.sysOrgService.searchOrgTreeByOrgNm("", CurrentThreadContext.getCurrentSysCd()); 
			}
			BaseLogUtils.info(logger, "initList", "初始化组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
			return jsonArray;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "初始化组织架构列表页面失败.系统错误:"+e.getMessage(),CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	/**
	 * 初始化列表一次性查出
	 *//*
	@RequestMapping(value = "/initListAll.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initListAll(HttpServletRequest request, HttpServletResponse response) {
		logger.info("==初始化列表数据.==");
		try {
			
			JSONArray jsonArray = this.sysOrgService.searchList();
			return jsonArray;
		} catch (Exception e) {
			logger.error("数据初始化失败", e);
		}
		return null;
	}*/
	/**
	 * 下拉树列表
	 *//*
	@RequestMapping(value = "/treeList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object treeList(HttpServletRequest request, HttpServletResponse response) {
		logger.info("==加载下拉树数据.==");
		String id =request.getParameter("id");
		try {
			
			JSONArray jsonArray = this.sysOrgService.searchList(Long.valueOf(id));
			return jsonArray;
		} catch (Exception e) {
			logger.error("加载失败", e);
		}
		return null;
	}*/

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeById", "删除组织架构,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {

			boolean success = this.sysOrgService.removeById(Long.valueOf(id));
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeById", "删除组织架构失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeById", "删除组织架构成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除组织架构失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除组织架构失败,系统错误.ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "获取组织架构数据,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysOrgVO vo = this.sysOrgService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取组织架构数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取组织架构数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取组织架构数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取组织架构数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysOrgVO entity = new SysOrgVO();
		try {
			entity = this.getRequestParamForSysOrgAddChild(request);
			Long id = this.sysOrgService.addSysOrgChild(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增组织架构成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增组织架构失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增组织架构失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		SysOrgVO entity = new SysOrgVO();
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改组织架构信息,主键参数为空！.ID:"+id, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity = this.getRequestParamForSysOrgModify(request);
			entity.setId(Long.valueOf(id));
			boolean success = this.sysOrgService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改组织架构数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改组织架构数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改组织架构数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改组织架构数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	/**
	 * 组织架构树-提供根据名称查询
	 */
	@RequestMapping(value = "/searchOrgTree.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object searchOrgTree(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String orgNm = request.getParameter("orgNm");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			JSONArray array = new JSONArray();
			array = this.sysOrgService.searchOrgTreeByOrgNm(orgNm, CurrentThreadContext.getCurrentSysCd());
			if(null == array){
				array = new JSONArray();
			}
			BaseLogUtils.info(logger, "searchOrgTree", "根据名称查询组织架构树成功.orgNm:"+orgNm, CurrentThreadContext.getCurrentUserName());
			result.setData(array);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "searchOrgTree", "根据名称查询组织架构树成功.orgNm:"+orgNm+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "searchOrgTree", "根据名称查询组织架构树成功.orgNm:"+orgNm+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	//***********************私有方法**********************//
	
	/**
	 * 获取组织架构请求参数(新增)
	 * @param request 请求
	 * @return 组织架构信息
	 */
	private SysOrgVO getRequestParamForSysOrgAdd(HttpServletRequest request)throws BaseException{
		
		String  orgDispNm = request.getParameter("orgDispNm");//架构名称
		String  orgShtNm = request.getParameter("orgShtNm");//架构名称
		String  orgNm = request.getParameter("orgNm");//架构名称
		String sortNo = request.getParameter("sortNo");// 排序编号
		String  orgTypCd= request.getParameter("orgTypCd");//架构类型
		String  orgRem= request.getParameter("orgRem");//架构描述
		String orgCd = request.getParameter("orgCd");//架构代码
		
		//验证 必填项 以及长度
		if(StringUtils.isBlank(orgDispNm) ){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "架构显示名称不能为空");
		}
		if(StringUtils.isBlank(orgShtNm) ){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "架构简称不能为空");
		}
		if(StringUtils.isBlank(orgNm) ){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "架构名称不能为空");
		}
		SysOrgVO sysOrgVO = new SysOrgVO();
		sysOrgVO.setOrgDispNm(orgDispNm);
		sysOrgVO.setOrgShtNm(orgShtNm);
		sysOrgVO.setOrgNm(orgNm);
		sysOrgVO.setOrgRem(orgRem);
		if(StringUtils.isNotBlank(sortNo) && StringUtils.isNumeric(sortNo)){
			sysOrgVO.setSortNo(Long.valueOf(sortNo));
		}else{
			sysOrgVO.setSortNo(0L);
		}
		sysOrgVO.setOrgTypCd(orgTypCd);
		sysOrgVO.setOrgCd(orgCd);
		sysOrgVO.setIsDel(BaseConstant.IS_YESNO_NO);
		sysOrgVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		return sysOrgVO;
		
	}
	
	/**
	 * 添加架构
	 */
	
	private  SysOrgVO getRequestParamForSysOrgAddChild(HttpServletRequest request)throws BaseException{
		String pid = request.getParameter("pid");
		SysOrgVO sysOrgVO = this.getRequestParamForSysOrgAdd(request);
		if(StringUtils.isNotBlank(pid)){
			sysOrgVO.setOrgPid(Long.valueOf(pid));
		}
		sysOrgVO.setCrtTm(new Date());
		sysOrgVO.setIsSysDef(BaseConstant.IS_YESNO_NO);
		sysOrgVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		return sysOrgVO;
	}
	
	/**
	 * 修改架构
	 */
	
	private  SysOrgVO getRequestParamForSysOrgModify(HttpServletRequest request)throws BaseException{
		SysOrgVO sysOrgVO = this.getRequestParamForSysOrgAdd(request);
		sysOrgVO.setMdfTm(new Date());
		sysOrgVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		return sysOrgVO;
	}
}

